import { DefaultContext, Next } from "koa";
import axios from "axios";
 
import { Response } from "../tools/response";
import { ProxyUrl } from "../config/basic";
import * as console from "console";
import { ErrorCode, ErrorMsg } from "../config/errorCode";
import { Sqlite } from "../db/sqlite";
import { readFile } from '../utils/tool'
class CwPublicController extends Sqlite {



    // 批量添加
    public addAppsBatch = async (ctx: DefaultContext, next: Next): Promise<any> => {
        const data = ctx.body;
        console.log(data)

        ctx.body = {
            "code": 20000,
            "msg": "成功",
            "timestamp": 0,
            "count": 21,
            "items": []
        }

        await next();
    }

    // 查询工具和业务列表
    public getAppList = async (ctx: DefaultContext, next: Next): Promise<any> => {

        const param = ctx.request.query
        console.log(param)

        const file: { appData: any[] } = await readFile('data/json/app.json')

        ctx.body = {
            "code": 20000,
            "msg": "成功",
            "timestamp": 0,
            "count": 21,
            "items": file.appData
        }

        await next();
    };

    public getAppCategoryList = async (ctx: DefaultContext, next: Next): Promise<any> => {

        const param = ctx.request.query

        console.log(param)

        ctx.body = {
            "code": 20000,
            "msg": "成功", "timestamp": 0, "items": [{ "id": 2, "name": "测试分类1" }]
        }


        await next();
    };


    // 添加对话记录
    public addChatHistory = async (ctx: DefaultContext, next: Next): Promise<any> => {

        const param = ctx.request.body;

        console.log(param)

        ctx.body = {
            "code": 20000,
            "msg": "成功",
            data: {}
        }


        await next();
    };


    // 获取对话记录
    public getChatHistory = async (ctx: DefaultContext, next: Next): Promise<any> => { 

        const param = ctx.request.body;

        console.log(param)
 

        ctx.body = {
            "code": 20000,
            "msg": "成功",
            timestamp: 0,
            items: {
                history: [{
                    way: 1,
                    count: 0,
                    data: [
                        {
                            app_id: 3,
                            logo: 'https://p5.itc.cn/images01/20230312/89e09e68f1b948fca07c6fa759a0fcf8.gif',
                            name: "代码生成",
                            is_select: false,
                        },
                        {
                            app_id: 1,
                            logo: 'https://p5.itc.cn/images01/20230312/89e09e68f1b948fca07c6fa759a0fcf8.gif',
                            name: "400客服",
                            is_select: false,
                        },
                        {
                            app_id: 2,
                            logo: 'https://p5.itc.cn/images01/20230312/89e09e68f1b948fca07c6fa759a0fcf8.gif',
                            name: "代码补全",
                            is_select: false,
                        }
                    ]
                },
                {
                    way: 2,
                    count: 0,
                    data: [
                        {
                            app_id: 3,
                            logo: 'https://p5.itc.cn/images01/20230312/89e09e68f1b948fca07c6fa759a0fcf8.gif',
                            name: "代码生成",
                            is_select: false,
                        },
                        {
                            app_id: 1,
                            logo: 'https://p5.itc.cn/images01/20230312/89e09e68f1b948fca07c6fa759a0fcf8.gif',
                            name: "400客服",
                            is_select: false,
                        },
                        {
                            app_id: 2,
                            logo: 'https://p5.itc.cn/images01/20230312/89e09e68f1b948fca07c6fa759a0fcf8.gif',
                            name: "代码补全",
                            is_select: false,
                        }
                    ]
                }],
                collect: [
                    {
                        app_id: 3,
                        logo: 'https://p5.itc.cn/images01/20230312/89e09e68f1b948fca07c6fa759a0fcf8.gif',
                        name: "代码生成",
                        is_select: false,
                    },
                    {
                        app_id: 1,
                        logo: 'https://p5.itc.cn/images01/20230312/89e09e68f1b948fca07c6fa759a0fcf8.gif',
                        name: "400客服",
                        is_select: false,
                    },
                    {
                        app_id: 2,
                        logo: 'https://p5.itc.cn/images01/20230312/89e09e68f1b948fca07c6fa759a0fcf8.gif',
                        name: "代码补全",
                        is_select: false,
                    }
                ],
                common: {
                    app_id: 2,
                    logo: 'https://p5.itc.cn/images01/20230312/89e09e68f1b948fca07c6fa759a0fcf8.gif',
                    name: "代码补全",
                    is_select: false,
                },
            }
        }


        await next();
    };

    // 获取对话记录
    public getAppById = async (ctx: DefaultContext, next: Next): Promise<any> => { 

        const param = ctx.request.query;

        console.log(param)
 

        ctx.body = {
            "code": 20000,
            "msg": "成功",
            timestamp: 0,
            items: {
               
            }
        }


        await next();
    };

      // 获取对话记录
    public getChatHistoryList = async (ctx: DefaultContext, next: Next): Promise<any> => {

        const param = ctx.request.body;

        console.log(param)
 

        ctx.body = {
            "code": 20000,
            "msg": "成功",
            timestamp: 0,
            items: [
                {
                    "id": 0,
                    "round_id": "string",
                    "role": "string",
                    "content": "string",
                    "created_at": '1710661020'
                  }
            ]
        }


        await next();
    };

    // 获取左侧菜单
    public getMenuTree = async (ctx: DefaultContext, next: Next): Promise<any> => {

        const param = ctx.request.query
        console.log(param)

        ctx.body = {
            code: 20000,
            msg: "成功",
            items: [
                { "id": 2, "name": "", "parent_id": '1', children: [] }]
        }


        await next();
    };

    // 获取左侧菜单
    public getMenuDetail = async (ctx: DefaultContext, next: Next): Promise<any> => {

        const param = ctx.request.query

        console.log(param)

        ctx.body = {
            "code": 20000,
            "msg": "成功", "timestamp": 0, "items": [{ "id": 2, "name": "测试分类1" }]
        }


        await next();
    };

    public ssoLogin = async (ctx: DefaultContext, next: Next): Promise<any> => {

        try {
            const param = ctx.request.query
            const header = ctx.request.headers

            const { channel_id } = param;

            const url = `${ProxyUrl}/api/v9/channels/${channel_id}/messages?limit=50`;

            const headers = { authorization: header.authorization };

            const response = await axios.get(url, { headers })

            ctx.body = response.data;
        } catch (e) {
            console.log(e)
            ctx.body = Response(ErrorCode.BadRequest, ErrorMsg.errorRequest, e)
        }
        await next();
    };



    // private async download(param: { _http: any; options: any; requestUrl: any; }): Promise<Buffer> {
    //
    //     const {_http, options, requestUrl} = param;
    //
    //     return new Promise((resolve, reject) => {
    //         const req = _http.request(options, (res: any) => {
    //
    //             console.log('开始下载图片(%s)', requestUrl)
    //
    //             // 判断数据是否为图片类型,仅保存图片类型
    //             const contentType = res.headers['content-type']
    //             if (contentType.startsWith('image')) {
    //                 // 存储图片数据到内存中
    //                 let chunks: any[] = []
    //                 res.on('data', (chunk: any) => {
    //                     chunks.push(chunk)
    //                 })
    //                 // req.on('abort') 中相同的操作也可以写在 res.on('aborted') 中
    //                 // res.on('aborted', () => {})
    //                 res.on('end', () => {
    //                     // 若响应正常结束,将内存中的数据写入到文件中
    //                     if (res.complete) {
    //                         console.log('图片(%s)下载完成', requestUrl)
    //                         resolve(Buffer.from(chunks))
    //                     } else {
    //                         console.log('(%s)下载结束但未完成', requestUrl)
    //
    //                     }
    //                 })
    //             }
    //         })
    //
    //         req.on('error', (err: string) => {
    //             console.error(err)
    //             reject(err)
    //         })
    //         req.on('abort', () => {
    //             console.log('下载(%s)被中断', requestUrl)
    //             reject("中断")
    //         })
    //         req.on('close', () => {
    //             console.log('下载(%s)被借宿', requestUrl)
    //         })
    //         // 如果超时则中止当前请求
    //         req.setTimeout(3 * 60 * 1000, () => {
    //             console.log('下载(%s)超时', requestUrl)
    //             req.abort()
    //         })
    //         req.end()
    //     })
    //
    // }
    //
    // public getPipe = async (ctx: DefaultContext, next: Next): Promise<any> => {
    //
    //     console.log(ctx.request.query);
    //
    //     const requestUrl = ctx.request.query.url;
    //
    //     console.log(requestUrl);
    //
    //     ctx.set('content-type', 'image/jpeg'); //设置返回类型
    //
    //     // URL作为options
    //     const options = new URL(requestUrl);
    //     // 获取协议
    //     const protocol = options.protocol
    //
    //     // 根据协议选择发送请求的模块
    //     const _http = protocol === 'HTTPS' ? https : http
    //
    //     // const matches = requestUrl.match(/(?<=.*\/)[^\/\?]+(?=\?|$)/)
    //     //
    //     // const fileName = matches && matches[0]
    //
    //     const result = await this.download({_http, options, requestUrl}).catch(error => {
    //         console.log(error);``
    //     })
    //
    //     if (!result) {
    //         ctx.status = 404;
    //         ctx.body = ''
    //         return ;
    //     }
    //
    //    ctx.body = new Blob([result], {type: 'image/jpeg'});
    //
    //     // 请求关闭时是否需要重新请求
    //
    //
    //     // try {
    //     //
    //     //     const result = await this.getBufferFromUrl(requestUrl).catch(error => {
    //     //         throw  new Error(error)
    //     //     })
    //     //
    //     //     if (!result) {
    //     //         throw "获取图片失败"
    //     //     }
    //     //
    //     //     ctx.body = new Blob([result], {type: 'image/jpeg'});
    //     //
    //     // } catch (error) {
    //     //     console.log(error.message);
    //     //     ctx.body = error.message;
    //     // }
    //
    //     await next();
    // };

    // 批量上传图片接口
    public uploadImage = async (ctx: DefaultContext, next: Next): Promise<any> => {

        const param = ctx.request.body

        console.log(param)


        await next();
    }


}

export default new CwPublicController();
